/**
* eCommerce Application Sample for J2EE Training 
* Implementation of EcomAdminBean
* @author Fabienne Boyer - Didier Donsez
* may 2006
*/

package ecom.beans.session;


import ecom.beans.entity.Accounts;
import ecom.beans.entity.Achats;
import ecom.beans.entity.Address;
import ecom.beans.entity.Category;
import ecom.beans.entity.Clients;
import ecom.beans.entity.Commandes;
import ecom.beans.entity.Productstore;
import ecom.beans.entity.Produits;
import ecom.exceptions.EcomException;
import java.util.Date;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


@Stateful
@Remote(EcomAdminRemote.class)
public class EcomAdminBean implements EcomAdminRemote{

    @PersistenceContext
    private EntityManager em;

     private boolean authentified = false;
    /**********************************
     * ACCOUNT
     **********************************/
/**
 *
 * @param accountId
 * @param accountOwner
 * @param balance
 */
    @Override
    public void createAccountUser(long ID_CLIENT, String accountOwner, double balance, String iban) {
        try {
            Clients user = em.find(Clients.class, ID_CLIENT);
            Accounts account = new Accounts(iban, accountOwner, balance,user);
            em.persist(account);
            user.getAccountsList().add(account);
        } catch (Exception e) {
            throw new EJBException(e);
        }
    }
    @Override
    public void createProductStore(int productStoreId, String city, int productStoreAccountId, String productStoreName) {
        try {
            System.out.println("creation de ProductStore fax " + productStoreName);
            Productstore productstore = new Productstore(city,productStoreName);

            productstore.setCity(city);
            productstore.setName(productStoreName);
            em.persist(productstore);
        } catch (Exception ex) {
            throw new EJBException(ex);
        }

    }
    @Override
    public void createProduct(String productName, double productPrice, long productStoreId, String description, String quantity, String url, long IdCategoty) {

        try {
            System.out.println("creation de Product");
            Category category = em.find(Category.class, IdCategoty);
            Productstore productstore = em.find(Productstore.class, productStoreId);
            Produits product = new Produits(productName, productPrice, description, quantity, url, category, productstore);
            em.persist(product);
        } catch (Exception ex) {
            throw new EJBException(ex);

        }
    }


    @Override
    //Renvoie 0 si le le password de l'administrateur est valid
    public int verifyAdminPassword(String login, String password) {
        if(login.equals("admin") && password.equals("admin")){
            this.authentified = true;
            return 0;
        }else{
            this.authentified = false;
            return -1;
        }

    }

    @Override
    public void deleteProduct(Long idProduct) {
       try {
            Produits product = em.find(Produits.class, idProduct);
            em.remove(product);
        } catch (Exception ex) {
            throw new EJBException(ex.getMessage());
        }
    }

    @Override
    public void deleteStore(Long idStore) {
        Productstore productstore = em.find(Productstore.class, idStore);
        em.remove(productstore);
    }
    @Override
    public void deleteCustomer(Long idClient){
         Clients clients= em.find(Clients.class, idClient);
         em.remove(clients);

    }
    @Override
    public void creditAccount(Long idCustomer, double sumAccount) {
         //Clients user = em.find(Clients.class, idCustomer);

          Accounts account = null;
         Query q = null;
        try {
            q = em.createNamedQuery("findUserAcount");
            q.setParameter("idUser", idCustomer);
            account = (Accounts) q.getSingleResult();
            account.deposit(sumAccount);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new EJBException(ex);
        }

    }

    @Override
    public List<Accounts> getAllAccount() {

        try {
            //System.out.println("appel de getAllAccount "+ em.toString());
             Query q = em.createNamedQuery("Accounts.findAll");
             //System.out.println("Fin appel de getAllAccount " +q.toString());
        List<Accounts> accounts = q.getResultList();
            return accounts;
        } catch (Throwable th) {
            throw new EcomException(th, 1);
        }

    }




    @Override
    public Clients getUserbyId(Long idUser){

          try{

          Query q =  em.createNamedQuery("Clients.findById");
           Clients clients = (Clients) q.getSingleResult();

          return clients;
        } catch (Throwable th) {
            throw new EcomException(th, 1);
        }
    }

    /**
     * Si l'authenfication de
     * @return
     */

    @Override
    public boolean isAdminAuthentified() {
                 return this.authentified;

    }
/*
    @Override
    public List<Productstore> getAllProductStore() {
        List<Productstore> productStores = null;
        try {
            productStores = em.createNamedQuery("findAllProductStore").getResultList();
            for (Productstore productStore : productStores){
                productStore.setAddress(getProductstoreAddress(productStore.getId()));
            }
            System.out.println(productStores.get(0).getAddress());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new EJBException(ex);
        }
        System.out.println(productStores.size() + "ont éte trouvé");
        return productStores;
    }*/

    @Override
    public List<Produits> getAllProduct() {
      List<Produits> products = null;
        try {
            System.out.println("get All Products");
            products = em.createNamedQuery("Produits.findAll").getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new EJBException(ex);
        }
        return products;
    }

    @Override
    public List<Produits> getProductsOfStore(Long idStore) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Productstore> getStoresOfProductCategory(Long idCategory) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Category> getAllProductCategory() {
         List<Category> productCategory = null;
        try {
            Query q = em.createNamedQuery("findAllCategory");
            productCategory = q.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new EJBException();
        }
        return productCategory;
    }

    @Override
    public Category getCategoryById(Long id) {
        Category productCategory = null;

        productCategory = em.find(Category.class, id);

        return productCategory;   }

    @Override
    public String getAllProductCategoryToString() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Clients> getAllCustomer() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Clients getCustomerById(Long id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Accounts getCustomerAccount(Long idUser) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Accounts getProductStoreAccount(Long idUser) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Address getCustomerAddress(Long idCustomer) {
        throw new UnsupportedOperationException("Not supported yet.");
    }


    @Override
    public List<Productstore> getAllProductStore() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Produits> getProductsOfCategory(Long idCatagory) {

       List<Produits> products = null;
        try {
            System.out.println("get  Products by Catagorie");

           Query q2 = em.createNamedQuery("Category.findProductsByIdCategory");
           q2.setParameter ("idCatagory", idCatagory);
            products = q2.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new EJBException(ex);
        }
        return products;
    }

    @Override
    public void createAchat(String city, String name, double price, String quantity, Commandes commandes, Produits produits) {
         try {
            System.out.println("creation de Achat");
            Achats achat = new Achats(city, name, price, quantity, commandes, produits);
            em.persist(achat);
        } catch (Exception ex) {
            throw new EJBException(ex);}
    }
@Override
public Commandes getCommandeByid(Long id){
    return em.find(Commandes.class, id);
}
    @Override
    public Commandes createCommande(Long idClient) {
         try {
            System.out.println("creation de Achat");
            Commandes commande = new Commandes(new Date() ,idClient);
            em.persist(commande);
            return commande;
        } catch (Exception ex) {
            throw new EJBException(ex);}

    }

    @Override
    public void UpdateUser(String prenom,String nom,String email,String password,String phone,int age) {

        try {
            Long id = null;
             Clients clients= em.find(Clients.class, id);
             clients.setPrenom(prenom);
             clients.setNom(nom);
             clients.setEmail(email);
             clients.setPassword(password);
             clients.setPhone(phone);
             clients.setAge(age);
            em.persist(clients);

        }catch (Exception ex) {
            throw new EJBException(ex);
        
    }

  // to be completed as needed
    }
}
